package com.agadmin.manage.handle.software;

import com.agadmin.api.Api;
import com.agadmin.entity.software.Software;
import com.agadmin.manage.ManageApiHandle;
import com.agadmin.manage.vo.reponse.software.SoftwareUpdateResponse;
import com.agadmin.manage.vo.request.software.SoftwareUpdateRequest;
import com.agadmin.mapper.SoftwareMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

@Transactional
@Slf4j
@Api
public class SoftwareUpdateManage implements ManageApiHandle<SoftwareUpdateRequest, SoftwareUpdateResponse> {

    @Resource
    SoftwareMapper softwareMapper;

    @Override
    public SoftwareUpdateResponse handler(SoftwareUpdateRequest softwareUpdateRequest) {

        SoftwareUpdateResponse res=new SoftwareUpdateResponse();

        Software software = querySoftware(softwareUpdateRequest.getId());
        if(software==null){
            res.setCode(403);
            res.setError("update fail,not found software");
            return res;
        }

        boolean update = updateSoftware(softwareUpdateRequest,software);
        if(!update){
            res.setCode(403);
            res.setError("update fail,duplicate name are found");
        }else {
            res.setCode(200);
            res.setMsg("update successful");
        }

        return res;
    }


    private boolean updateSoftware(SoftwareUpdateRequest req,Software soft) {
        Software software = new Software();
        BeanUtils.copyProperties(req, software, "id", "createTime");
        software.setId(req.getId());
        if(Objects.equals(software.getSoftwareName(), soft.getSoftwareName())){
            software.setSoftwareName(null);
        }
        LambdaQueryWrapper<Software> qw = new LambdaQueryWrapper();
        qw.eq(req.getId() != null, Software::getId, req.getId());
        try {
            int update = softwareMapper.update(software, qw);

            return update > 0;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    private Software querySoftware(String id){
        Software software = softwareMapper.selectById(id);
        return software;
    }
}
